import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../../models/notice.dart';
import '../../models/notification_message.dart';
import '../../models/community_post.dart';
import '../../services/websocket_manager.dart';
import '../../services/community_service.dart';
import 'package:intl/intl.dart';

class NotificationsPage extends StatefulWidget {
  const NotificationsPage({super.key});

  @override
  State<NotificationsPage> createState() => _NotificationsPageState();
}

class _NotificationsPageState extends State<NotificationsPage> with TickerProviderStateMixin {
  List<Notice> _notifications = [];
  List<NotificationMessage> _messages = [];
  bool _isLoading = true;
  int _selectedTabIndex = 0; // 0: 系统通知, 1: 消息通知
  final WebSocketManager _wsManager = WebSocketManager();
  final CommunityService _communityService = CommunityService();
  
  // 滑动动画控制器
  final Map<String, AnimationController> _slideControllers = {};
  final Map<String, Animation<Offset>> _slideAnimations = {};

  @override
  void initState() {
    super.initState();
    _loadNotifications();
    _loadMessages();
  }

  @override
  void dispose() {
    // 释放动画控制器
    for (var controller in _slideControllers.values) {
      controller.dispose();
    }
    super.dispose();
  }

  /// 获取滑动动画
  Animation<Offset> _getSlideAnimation(String messageId) {
    if (!_slideAnimations.containsKey(messageId)) {
      final controller = AnimationController(
        duration: const Duration(milliseconds: 200),
        vsync: this,
      );
      _slideControllers[messageId] = controller;
      
      final animation = Tween<Offset>(
        begin: Offset.zero,
        end: const Offset(-0.2, 0), // 向左滑动20%的宽度
      ).animate(CurvedAnimation(
        parent: controller,
        curve: Curves.easeInOut,
      ));
      _slideAnimations[messageId] = animation;
    }
    return _slideAnimations[messageId]!;
  }

  void _loadNotifications() {
    // 模拟加载延迟
    Future.delayed(const Duration(milliseconds: 800), () {
      if (mounted) {
        setState(() {
          _notifications = _getMockNotifications();
          _isLoading = false;
        });
      }
    });
  }

  void _loadMessages() {
    // 监听离线消息变化
    _wsManager.offlineMessageService.messagesStream.listen((messages) {
      if (mounted) {
        setState(() {
          _messages = messages;
        });
      }
    });
    
    // 初始加载消息
    _wsManager.offlineMessageService.getOfflineMessages().then((messages) {
      if (mounted) {
        setState(() {
          _messages = messages;
        });
      }
    });
  }

  List<Notice> _getMockNotifications() {
    return [
      Notice(
        id: 1,
        title: '春季钓鱼大赛开始报名',
        content: '2024年春季钓鱼大赛即将开始，报名时间截止到本月底，奖品丰厚，欢迎各位钓友踊跃参加！',
        publisher: '渔乐圈官方',
        publishTime: '2024-03-15 10:30',
        status: 'unread',
      ),
      Notice(
        id: 2,
        title: '新钓场开业优惠活动',
        content: '蓝湖钓场新店开业，前100名顾客享受8折优惠，还有精美钓具赠送，地址：市区东湖路88号',
        publisher: '蓝湖钓场',
        publishTime: '2024-03-14 16:20',
        status: 'read',
      ),
      Notice(
        id: 3,
        title: '钓技分享会邀请函',
        content: '本周六下午2点，在钓友俱乐部举办钓技分享会，邀请资深钓友分享春季钓鱼技巧，免费参加。',
        publisher: '钓友俱乐部',
        publishTime: '2024-03-13 09:15',
        status: 'read',
      ),
      Notice(
        id: 4,
        title: '天气预警提醒',
        content: '明日有中到大雨，不适宜户外钓鱼活动，请各位钓友注意安全，合理安排出行计划。',
        publisher: '天气助手',
        publishTime: '2024-03-12 18:45',
        status: 'unread',
      ),
      Notice(
        id: 5,
        title: '钓具保养小贴士',
        content: '春季来临，是时候给你的钓具做个全面保养了！定期清洁和维护能延长钓具使用寿命。',
        publisher: '钓具专家',
        publishTime: '2024-03-11 14:30',
        status: 'read',
      ),
      Notice(
        id: 6,
        title: '社区活动通知',
        content: '下周三晚上7点，钓友圈线下聚会，地点在市中心咖啡厅，欢迎大家参加交流钓鱼心得。',
        publisher: '社区管理员',
        publishTime: '2024-03-10 11:20',
        status: 'read',
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        backgroundColor: const Color(0xFFF5F5F5),
        appBar: AppBar(
          title: const Text(
            '通知',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: Colors.black87,
            ),
          ),
          backgroundColor: Colors.white,
          elevation: 0,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back, color: Colors.black87),
            onPressed: () => context.pop(),
          ),
          actions: [
            if (_selectedTabIndex == 1) // 只在消息标签页显示全部已读按钮
              IconButton(
                icon: const Icon(Icons.done_all, color: Colors.black87),
                onPressed: _markAllMessagesAsRead,
                tooltip: '全部已读',
              ),
            IconButton(
              icon: const Icon(Icons.more_vert, color: Colors.black87),
              onPressed: _showMoreOptions,
            ),
          ],
          bottom: TabBar(
            onTap: (index) {
              setState(() {
                _selectedTabIndex = index;
              });
            },
            labelColor: const Color(0xFF2196F3),
            unselectedLabelColor: Colors.grey,
            indicatorColor: const Color(0xFF2196F3),
            tabs: [
              const Tab(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.notifications),
                    SizedBox(width: 4),
                    Text('系统通知'),
                  ],
                ),
              ),
              Tab(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const Icon(Icons.message),
                    const SizedBox(width: 4),
                    const Text('消息'),
                    if (_getUnreadMessageCount() > 0)
                      Container(
                        margin: const EdgeInsets.only(left: 4),
                        padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                        decoration: BoxDecoration(
                          color: Colors.red,
                          borderRadius: BorderRadius.circular(10),
                        ),
                        child: Text(
                          '${_getUnreadMessageCount()}',
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 10,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                  ],
                ),
              ),
            ],
          ),
        ),
        body: _isLoading
            ? const Center(
                child: CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF2196F3)),
                ),
              )
            : TabBarView(
                children: [
                  _buildSystemNotifications(),
                  _buildMessageNotifications(),
                ],
              ),
      ),
    );
  }


  /// 构建消息卡片（支持右滑显示删除按钮）
  Widget _buildMessageCard(NotificationMessage message, int index) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: Stack(
          children: [
            // 删除按钮背景（隐藏在右侧）
            Positioned.fill(
              child: Container(
                color: Colors.red,
                alignment: Alignment.centerRight,
                padding: const EdgeInsets.only(right: 20),
                child: GestureDetector(
                  onTap: () => _onDeleteButtonTap(message, index),
                  child: Container(
                    width: 80,
                    height: double.infinity,
                    color: Colors.red,
                    child: const Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.delete,
                          color: Colors.white,
                          size: 24,
                        ),
                        SizedBox(height: 4),
                        Text(
                          '删除',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
            // 可滑动的消息内容
            SlideTransition(
              position: _getSlideAnimation(message.id),
              child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.05),
                blurRadius: 10,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Material(
            color: Colors.transparent,
            child: GestureDetector(
              onHorizontalDragUpdate: (details) {
                _onHorizontalDragUpdate(message.id, details);
              },
              onHorizontalDragEnd: (details) {
                _onHorizontalDragEnd(message.id, details);
              },
              child: InkWell(
                borderRadius: BorderRadius.circular(12),
                onTap: () => _onMessageTap(message),
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 消息图标
                    Container(
                      width: 40,
                      height: 40,
                      decoration: BoxDecoration(
                        color: _getMessageColor(message).withOpacity(0.1),
                        borderRadius: BorderRadius.circular(20),
                      ),
                      child: Center(
                        child: Text(
                          message.getNotificationIcon(),
                          style: const TextStyle(fontSize: 20),
                        ),
                      ),
                    ),
                    const SizedBox(width: 12),
                    // 消息内容
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Expanded(
                                child: Text(
                                  message.title,
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: message.isRead ? FontWeight.normal : FontWeight.bold,
                                    color: Colors.black87,
                                  ),
                                ),
                              ),
                              if (!message.isRead)
                                Container(
                                  width: 8,
                                  height: 8,
                                  decoration: const BoxDecoration(
                                    color: Colors.red,
                                    shape: BoxShape.circle,
                                  ),
                                ),
                            ],
                          ),
                          const SizedBox(height: 4),
                          Text(
                            message.content,
                            style: TextStyle(
                              fontSize: 14,
                              color: Colors.grey[600],
                              height: 1.4,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          const SizedBox(height: 8),
                          Row(
                            children: [
                              if (message.senderName != null) ...[
                                Text(
                                  message.senderName!,
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: Colors.grey[500],
                                  ),
                                ),
                                const SizedBox(width: 8),
                              ],
                              Text(
                                _formatMessageTime(message.timestamp),
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Colors.grey[500],
                                ),
                              ),
                              if (message.isOffline) ...[
                                const SizedBox(width: 8),
                                Container(
                                  padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                                  decoration: BoxDecoration(
                                    color: Colors.orange.withOpacity(0.1),
                                    borderRadius: BorderRadius.circular(4),
                                  ),
                                  child: Text(
                                    '离线',
                                    style: TextStyle(
                                      fontSize: 10,
                                      color: Colors.orange[700],
                                    ),
                                  ),
                                ),
                              ],
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    ),
          ],
        ),
      ),
    );
  }

  /// 处理水平拖拽更新
  void _onHorizontalDragUpdate(String messageId, DragUpdateDetails details) {
    final controller = _slideControllers[messageId];
    if (controller != null) {
      // 只允许向左滑动，限制滑动距离
      final delta = details.primaryDelta! / context.size!.width;
      final newValue = (controller.value - delta * 2).clamp(0.0, 1.0);
      controller.value = newValue;
    }
  }

  /// 处理水平拖拽结束
  void _onHorizontalDragEnd(String messageId, DragEndDetails details) {
    final controller = _slideControllers[messageId];
    if (controller != null) {
      // 根据滑动速度和位置决定是否显示删除按钮
      if (controller.value > 0.3 || details.primaryVelocity! < -500) {
        // 显示删除按钮
        controller.forward();
      } else {
        // 回弹到原位
        controller.reverse();
      }
    }
  }

  /// 点击删除按钮
  void _onDeleteButtonTap(NotificationMessage message, int index) async {
    // 先隐藏删除按钮
    final controller = _slideControllers[message.id];
    controller?.reverse();
    
    // 显示删除确认对话框
    final confirmed = await _showDeleteConfirmDialog(message);
    if (confirmed == true) {
      _deleteMessageWithAnimation(message, index);
    }
  }

  /// 获取消息颜色
  Color _getMessageColor(NotificationMessage message) {
    switch (message.type) {
      case 'comment_reply':
      case 'post_reply':
        return const Color(0xFF2196F3);
      case 'like':
        return const Color(0xFFFF5722);
      case 'follow':
        return const Color(0xFF4CAF50);
      case 'system':
        return const Color(0xFF9C27B0);
      default:
        return const Color(0xFF757575);
    }
  }

  /// 格式化消息时间
  String _formatMessageTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);
    
    if (difference.inMinutes < 1) {
      return '刚刚';
    } else if (difference.inHours < 1) {
      return '${difference.inMinutes}分钟前';
    } else if (difference.inDays < 1) {
      return '${difference.inHours}小时前';
    } else if (difference.inDays < 7) {
      return '${difference.inDays}天前';
    } else {
      return DateFormat('MM-dd HH:mm').format(time);
    }
  }

  /// 处理消息点击
  void _onMessageTap(NotificationMessage message) {
    // 标记为已读
    if (!message.isRead) {
      _wsManager.offlineMessageService.markMessageAsRead(message.id);
    }
    
    // 使用导航路径进行跳转
    if (message.navigationPath != null && message.navigationPath!.isNotEmpty) {
      _navigateWithPath(message);
    } else {
      // 如果没有导航路径，显示消息详情
      _showMessageDetail(message);
    }
  }

  /// 使用导航路径进行跳转
  void _navigateWithPath(NotificationMessage message) async {
    final navigationPath = message.navigationPath!;
    final navigationParams = message.navigationParams ?? {};
    
    // 显示加载对话框
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        content: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            const CircularProgressIndicator(),
            const SizedBox(width: 16),
            Text(_getLoadingText(message.type)),
          ],
        ),
      ),
    );

    try {
      // 根据导航路径类型进行不同的处理
      if (navigationPath.startsWith('/community/')) {
        await _handleCommunityNavigation(message, navigationPath, navigationParams);
      } else if (navigationPath.startsWith('/profile/')) {
        await _handleProfileNavigation(message, navigationPath, navigationParams);
      } else {
        // 其他类型的导航，直接跳转
        await _handleGenericNavigation(message, navigationPath, navigationParams);
      }
    } catch (e) {
      if (mounted) {
        Navigator.pop(context); // 关闭加载对话框
        _showErrorAndFallback(message, '导航失败: $e');
      }
    }
  }

  /// 获取加载文本
  String _getLoadingText(String messageType) {
    switch (messageType) {
      case 'comment_reply':
      case 'post_reply':
        return '正在加载帖子...';
      case 'follow':
        return '正在加载用户资料...';
      default:
        return '正在加载...';
    }
  }

  /// 处理钓友圈相关导航
  Future<void> _handleCommunityNavigation(
    NotificationMessage message, 
    String navigationPath, 
    Map<String, dynamic> navigationParams
  ) async {
    final postId = navigationParams['postId']?.toString() ?? 
                   _extractPostIdFromPath(navigationPath);
    
    if (postId == null || postId.isEmpty) {
      throw Exception('无效的帖子ID');
    }

    final postIdInt = int.tryParse(postId);
    if (postIdInt == null || postIdInt <= 0) {
      throw Exception('无效的帖子ID格式');
    }

    final result = await _communityService.getCommunityPostDetail(postIdInt);
    
    if (mounted) {
      Navigator.pop(context); // 关闭加载对话框
      
      if (result['success'] == true && result['data'] != null) {
        final post = result['data'] as CommunityPost;
        // 导航到帖子详情页，直接传递CommunityPost对象
        context.push(navigationPath, extra: post);
      } else {
        _showErrorAndFallback(message, result['message'] ?? '获取帖子失败');
      }
    }
  }

  /// 处理用户资料相关导航
  Future<void> _handleProfileNavigation(
    NotificationMessage message, 
    String navigationPath, 
    Map<String, dynamic> navigationParams
  ) async {
    // 模拟加载用户资料数据
    await Future.delayed(const Duration(milliseconds: 500));
    
    if (mounted) {
      Navigator.pop(context); // 关闭加载对话框
      
      // 跳转到用户资料页面
      context.push(navigationPath, extra: navigationParams);
    }
  }

  /// 处理通用导航
  Future<void> _handleGenericNavigation(
    NotificationMessage message, 
    String navigationPath, 
    Map<String, dynamic> navigationParams
  ) async {
    // 模拟加载
    await Future.delayed(const Duration(milliseconds: 300));
    
    if (mounted) {
      Navigator.pop(context); // 关闭加载对话框
      
      // 直接跳转
      context.push(navigationPath, extra: navigationParams);
    }
  }

  /// 从路径中提取帖子ID
  String? _extractPostIdFromPath(String path) {
    final regex = RegExp(r'/community/(\d+)');
    final match = regex.firstMatch(path);
    return match?.group(1);
  }

  /// 显示错误信息并回退到消息详情
  void _showErrorAndFallback(NotificationMessage message, String error) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(error),
        backgroundColor: Colors.red,
        action: SnackBarAction(
          label: '查看详情',
          textColor: Colors.white,
          onPressed: () => _showMessageDetail(message),
        ),
      ),
    );
  }


  /// 显示删除确认对话框
  Future<bool?> _showDeleteConfirmDialog(NotificationMessage message) async {
    return await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除消息'),
        content: Text('确定要删除这条消息吗？\n\n"${message.title}"'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            style: TextButton.styleFrom(
              foregroundColor: Colors.red,
            ),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  /// 删除消息并显示动画
  void _deleteMessageWithAnimation(NotificationMessage message, int index) async {
    try {
      // 显示删除中的提示
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Row(
            children: [
              const SizedBox(
                width: 16,
                height: 16,
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                ),
              ),
              const SizedBox(width: 12),
              const Text('正在删除消息...'),
            ],
          ),
          duration: const Duration(seconds: 2),
        ),
      );

      // 调用删除API
      await _wsManager.offlineMessageService.deleteMessage(message.id);
      
      // 显示删除成功提示
      if (mounted) {
        ScaffoldMessenger.of(context).hideCurrentSnackBar();
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                const Icon(Icons.check, color: Colors.white),
                const SizedBox(width: 8),
                Text('已删除"${message.title}"'),
              ],
            ),
            backgroundColor: Colors.green,
            duration: const Duration(seconds: 2),
            action: SnackBarAction(
              label: '撤销',
              textColor: Colors.white,
              onPressed: () {
                // TODO: 实现撤销删除功能
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('撤销功能开发中...'),
                    duration: Duration(seconds: 1),
                  ),
                );
              },
            ),
          ),
        );
      }
    } catch (e) {
      // 删除失败，显示错误提示
      if (mounted) {
        ScaffoldMessenger.of(context).hideCurrentSnackBar();
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                const Icon(Icons.error, color: Colors.white),
                const SizedBox(width: 8),
                Text('删除失败: $e'),
              ],
            ),
            backgroundColor: Colors.red,
            duration: const Duration(seconds: 3),
            action: SnackBarAction(
              label: '重试',
              textColor: Colors.white,
              onPressed: () => _deleteMessageWithAnimation(message, index),
            ),
          ),
        );
      }
    }
  }

  /// 显示消息详情
  void _showMessageDetail(NotificationMessage message) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(message.title),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(message.content),
            const SizedBox(height: 16),
            if (message.senderName != null) ...[
              Text(
                '发送者：${message.senderName}',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey[600],
                ),
              ),
              const SizedBox(height: 4),
            ],
            Text(
              '时间：${DateFormat('yyyy-MM-dd HH:mm:ss').format(message.timestamp)}',
              style: TextStyle(
                fontSize: 12,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  /// 构建通知卡片（重命名原有方法）
  Widget _buildNotificationCard(Notice notification, int index) {
    return _buildNotificationItem(notification, index);
  }


  Widget _buildNotificationItem(Notice notification, int index) {
    final isUnread = notification.status == 'unread';
    
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: isUnread 
            ? Border.all(color: Colors.blue[200]!, width: 1)
            : null,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withAlpha((0.05 * 255).round()),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          borderRadius: BorderRadius.circular(12),
          onTap: () => _onNotificationTap(notification),
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 未读标识
                    if (isUnread)
                      Container(
                        width: 8,
                        height: 8,
                        margin: const EdgeInsets.only(top: 6, right: 12),
                        decoration: BoxDecoration(
                          color: Colors.blue[600],
                          shape: BoxShape.circle,
                        ),
                      ),
                    // 通知图标
                    Container(
                      width: 40,
                      height: 40,
                      decoration: BoxDecoration(
                        color: _getNotificationIconColor(notification).withAlpha((0.1 * 255).round()),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Icon(
                        _getNotificationIcon(notification),
                        color: _getNotificationIconColor(notification),
                        size: 20,
                      ),
                    ),
                    const SizedBox(width: 12),
                    // 通知内容
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            notification.title ?? '无标题',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: isUnread ? FontWeight.w600 : FontWeight.w500,
                              color: Colors.black87,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          const SizedBox(height: 6),
                          Text(
                            notification.content ?? '无内容',
                            style: TextStyle(
                              fontSize: 14,
                              color: Colors.grey[600],
                              height: 1.4,
                            ),
                            maxLines: 3,
                            overflow: TextOverflow.ellipsis,
                          ),
                          const SizedBox(height: 8),
                          Row(
                            children: [
                              Icon(
                                Icons.person_outline,
                                size: 14,
                                color: Colors.grey[500],
                              ),
                              const SizedBox(width: 4),
                              Text(
                                notification.publisher ?? '未知发布者',
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Colors.grey[500],
                                ),
                              ),
                              const Spacer(),
                              Icon(
                                Icons.access_time,
                                size: 14,
                                color: Colors.grey[500],
                              ),
                              const SizedBox(width: 4),
                              Text(
                                _formatTime(notification.publishTime),
                                style: TextStyle(
                                  fontSize: 12,
                                  color: Colors.grey[500],
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  IconData _getNotificationIcon(Notice notification) {
    final title = notification.title?.toLowerCase() ?? '';
    if (title.contains('比赛') || title.contains('大赛')) {
      return Icons.emoji_events;
    } else if (title.contains('天气') || title.contains('预警')) {
      return Icons.cloud;
    } else if (title.contains('活动') || title.contains('聚会')) {
      return Icons.event;
    } else if (title.contains('钓场') || title.contains('优惠')) {
      return Icons.store;
    } else if (title.contains('技巧') || title.contains('分享')) {
      return Icons.school;
    } else {
      return Icons.notifications;
    }
  }

  Color _getNotificationIconColor(Notice notification) {
    final title = notification.title?.toLowerCase() ?? '';
    if (title.contains('比赛') || title.contains('大赛')) {
      return Colors.amber[600]!;
    } else if (title.contains('天气') || title.contains('预警')) {
      return Colors.orange[600]!;
    } else if (title.contains('活动') || title.contains('聚会')) {
      return Colors.green[600]!;
    } else if (title.contains('钓场') || title.contains('优惠')) {
      return Colors.purple[600]!;
    } else if (title.contains('技巧') || title.contains('分享')) {
      return Colors.teal[600]!;
    } else {
      return Colors.blue[600]!;
    }
  }

  String _formatTime(String? timeStr) {
    if (timeStr == null || timeStr.isEmpty) return '未知时间';
    
    try {
      // 简单的时间格式化，实际项目中可以使用 intl 包
      final parts = timeStr.split(' ');
      if (parts.length >= 2) {
        final datePart = parts[0];
        final timePart = parts[1];
        final dateComponents = datePart.split('-');
        if (dateComponents.length >= 3) {
          final month = dateComponents[1];
          final day = dateComponents[2];
          return '$month-$day ${timePart.substring(0, 5)}';
        }
      }
      return timeStr;
    } catch (e) {
      return timeStr;
    }
  }

  void _onNotificationTap(Notice notification) {
    // 如果是未读状态，标记为已读
    if (notification.status == 'unread') {
      setState(() {
        // 创建新的Notice对象来替换原来的
        final index = _notifications.indexOf(notification);
        if (index != -1) {
          _notifications[index] = Notice(
            id: notification.id,
            title: notification.title,
            imageUrl: notification.imageUrl,
            content: notification.content,
            publisher: notification.publisher,
            publishTime: notification.publishTime,
            status: 'read', // 更新状态为已读
            createBy: notification.createBy,
            createTime: notification.createTime,
            updateBy: notification.updateBy,
            updateTime: notification.updateTime,
            remark: notification.remark,
          );
        }
      });
    }

    // 显示通知详情
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(notification.title ?? '通知详情'),
        content: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                notification.content ?? '无内容',
                style: const TextStyle(fontSize: 16, height: 1.5),
              ),
              const SizedBox(height: 16),
              Row(
                children: [
                  Icon(Icons.person_outline, size: 16, color: Colors.grey[600]),
                  const SizedBox(width: 4),
                  Text(
                    '发布者：${notification.publisher ?? '未知'}',
                    style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Row(
                children: [
                  Icon(Icons.access_time, size: 16, color: Colors.grey[600]),
                  const SizedBox(width: 4),
                  Text(
                    '发布时间：${notification.publishTime ?? '未知'}',
                    style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                  ),
                ],
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  /// 获取未读消息数量
  int _getUnreadMessageCount() {
    return _messages.where((msg) => !msg.isRead).length;
  }

  /// 标记所有消息为已读
  Future<void> _markAllMessagesAsRead() async {
    await _wsManager.offlineMessageService.markAllMessagesAsRead();
  }

  /// 显示更多选项
  void _showMoreOptions() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.delete_sweep),
              title: const Text('清空所有消息'),
              onTap: () {
                Navigator.pop(context);
                _clearAllMessages();
              },
            ),
          ],
        ),
      ),
    );
  }

  /// 清空所有消息
  Future<void> _clearAllMessages() async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认清空'),
        content: const Text('确定要清空所有消息吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('确定'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      await _wsManager.offlineMessageService.clearAllMessages();
    }
  }

  /// 构建系统通知页面
  Widget _buildSystemNotifications() {
    if (_notifications.isEmpty) {
      return _buildEmptyState('暂无系统通知');
    }
    
    return RefreshIndicator(
      onRefresh: () async {
        // 模拟刷新
        await Future.delayed(const Duration(seconds: 1));
        setState(() {
          _notifications = _getMockNotifications();
        });
      },
      child: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: _notifications.length,
        itemBuilder: (context, index) {
          final notification = _notifications[index];
          return _buildNotificationCard(notification, index);
        },
      ),
    );
  }

  /// 构建消息通知页面
  Widget _buildMessageNotifications() {
    if (_messages.isEmpty) {
      return _buildEmptyState('暂无消息通知');
    }
    
    return RefreshIndicator(
      onRefresh: () async {
        // 刷新消息
        await _wsManager.offlineMessageService.syncOfflineMessages();
      },
      child: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: _messages.length,
        itemBuilder: (context, index) {
          final message = _messages[index];
          return _buildMessageCard(message, index);
        },
      ),
    );
  }

  /// 构建空状态页面
  Widget _buildEmptyState([String? message]) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.notifications_off_outlined,
            size: 80,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            message ?? '暂无通知消息',
            style: TextStyle(
              fontSize: 16,
              color: Colors.grey[600],
              fontWeight: FontWeight.w500,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '有新消息时会在这里显示',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[500],
            ),
          ),
        ],
      ),
    );
  }
}